﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace XAMLDecompiler
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void PickDirectory(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "Pick the directory containing the .xbf files you want to convert.";
            dialog.RootFolder = Environment.SpecialFolder.Desktop;
            dialog.ShowNewFolderButton = true;

            var result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
                PathText.Text = dialog.SelectedPath;
            else
                PathText.Text = "";
        }

        private void ConvertFiles(object sender, RoutedEventArgs e)
        {
            if (PathText.Text == "")
                return;

            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(PathText.Text);
            System.IO.FileInfo[] files = dir.GetFiles();
            LogBox.AppendText(String.Format("Found {0} .xbf files in folder.\n",files.Length));

            var engine = typeof(Microsoft.Build.ILTasks.ReducerEngine.AnalysisEngine);
            var reader = engine.Assembly.GetType("Xbf2Xaml.XBFReader");
            var constructor = reader.GetConstructor(new Type[] { typeof(string), engine });

            LogBox.AppendText("Converting .xbf files in .xaml....\n\n");
            for (int i = 0; i < files.Length; i++)
            {
                LogBox.AppendText(String.Format("Converting: {0}\n",files[i].Name));
                var worker = constructor.Invoke(new[] { files[i].FullName, null });
                var method = reader.GetMethod("ReadXBFFile");
                var xaml = method.Invoke(worker, new object[] { });
                LogBox.AppendText("Writing XAML file..\n");
                WriteFile(xaml.ToString(), files[i].Name);
                LogBox.AppendText(String.Format("Done with: {0}\n\n", files[i].Name));
            }
        }

        private void WriteFile(String _inputXaml, String _fileName)
        {
            String fname = String.Format("{0}/{1}.xaml", PathText.Text, _fileName);
            using (StreamWriter sr = new StreamWriter(fname))
            {
                sr.WriteLine(_inputXaml);
            }
        }
    }
}
